package tk.mynoteapp.dev.common;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpUtil {
    private static CloseableHttpClient httpClient = createSSLClientDefault();

    public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException {
        // https://api.yongcheng.com:19090/apigateway/extra/111
        // http://test.yongcheng.com/apigateway/extra/111
//        doGet("https://api.yongcheng.com:19090/apigateway/extra/111");
        doPost("https://api.yongcheng.com:19090/apigateway/extra/111", "{\"test\":\"001\"}", "UTF-8");
    }

    public static String doGet(String url) throws NoSuchAlgorithmException, KeyManagementException {
//        RequestConfig.Builder builder = RequestConfig.custom();
//        builder.setSocketTimeout(1500);
//        builder.setConnectTimeout(1500);
//        builder.setConnectionRequestTimeout(1500);
//        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(builder.build()).build();


        HttpGet httpGet = new HttpGet();
        try {
            httpGet.setURI(new URI(url));
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity);
            } else {
                System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                throw new RuntimeException("连接" + url + "返回有误，状态码：" + statusCode);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpGet != null) {
                httpGet.releaseConnection();
            }
        }
        return null;
    }

    public static String doPost(String url, String data, String charset) throws NoSuchAlgorithmException, KeyManagementException {
        HttpPost httpPost = new HttpPost();
        try {
            httpPost.setURI(new URI(url));
            StringEntity content = new StringEntity(data, Charset.forName(charset));
            content.setContentType("application/json");
            content.setContentEncoding(charset);
            httpPost.setEntity(content);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                return EntityUtils.toString(entity);
            } else {
                System.out.println(EntityUtils.toString(httpResponse.getEntity()));
                throw new RuntimeException("连接" + url + "返回有误，状态码：" + statusCode);
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return null;
    }

    public static CloseableHttpClient createSSLClientDefault() {
        SSLContext sslContext = null;
        try {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setSocketTimeout(15000); // 15秒（15000毫秒） 数据传输过程中数据包之间间隔的最大时间
        builder.setConnectTimeout(15000); // 连接建立时间，三次握手完成时间
        builder.setConnectionRequestTimeout(15000); // 从连接池获取连接的超时时间

        HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(builder.build()).setSSLSocketFactory(sslsf);
        return httpClientBuilder.build();
    }


}
